$("#mfile").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=goodssku',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpic").val(data.response.data);
})
$("#mfile2").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=goodssku',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpic2").val(data.response.data);
})

function shareBonusTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 0)
        return "无奖励";
    else if (value == 1)
        return "送积分";
    else if (value == 2)
        return "送现金";
    else if (value == 3)
        return "送优惠券";
    else return ""
}

function gtypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "实物产品";
    else if (value == 2)
        return "虚拟产品";
    else if (value == 3)
        return "预约到店服务";
    else if (value == 4)
        return "预约上门服务";
    else return ""
}

function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/goodssku/list'});
        },
        dataType: "json"
    });
}

function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/goodssku/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

var editsw = [];
/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)

    modal.find('#id').val(data.id)
    modal.find('#cid').val(data.cid)
    modal.find('#characteristic').val(data.characteristic)
    modal.find('#logisticsId').val(data.logisticsId)
    modal.find('#minPrice').val(data.minPrice)
    modal.find('#price').val(data.price)
    modal.find('#saleprice').val(data.saleprice)
    modal.find('#name').val(data.name)
    modal.find('#goodsNo').val(data.goodsNo)
    modal.find('#ext1').val(data.ext1)
    modal.find('#ext2').val(data.ext2)
    modal.find('#ext3').val(data.ext3)
    modal.find('#ext4').val(data.ext4)
    modal.find('#ext5').val(data.ext5)
    modal.find('#numberFav').val(data.numberFav)
    modal.find('#numberGrade').val(data.numberGrade)
    modal.find('#numberOrders').val(data.numberOrders)
    modal.find('#numberSale').val(data.numberSale)
    modal.find('#paixu').val(data.paixu)
    modal.find('#dateStart').val(data.dateStart)
    modal.find('#dateEnd').val(data.dateEnd)
    modal.find('#propertyIds').val(data.propertyIds)
    modal.find('#recommend').val(data.recommend)
    $('#sninfo2').code(data.info);
    $('#info2').val(data.info);
    editsw["state"] == undefined ? editsw["state"] = new Switchery(document.querySelector('#state'), {color: "#1AB394"}) : ""
    if (data.state == 1) {
        setSwitchery(editsw["state"], true);
    } else {
        setSwitchery(editsw["state"], false);
    }
    modal.find('#stores').val(data.stores)
    modal.find('#videoId').val(data.videoId)
    // 此部分需要注意：如果页面有两个以上的图片编辑
    // 该部分逻辑需要重写
    $("#mFile").fileinput('refresh', {
        initialPreview: [ //预览图片的设置
            "<img src='" + data.pic + "' class='file-preview-image' alt='' title=''>",
        ],
    });
    $("#previewPic").attr("src", data.pic);

    modal.find('#maxUseCoupon').val(data.maxUseCoupon)
    modal.find('#shareBonusType').find("option[value='" + data['shareBonusType'] + "']").attr("selected", true);
    modal.find('#shareMount').val(data.shareMount)
    modal.find('#barcode').val(data.barcode)
    modal.find('#weight').val(data.weight)
    modal.find('#views').val(data.views)
    modal.find('#type').find("option[value='" + data['type'] + "']").attr("selected", true);
    modal.find('#userId').val(data.userId)
    modal.find('#mpid').val(data.mpid)
    modal.find('#eventId').val(data.eventId)
    editsw["isMember"] == undefined ? editsw["isMember"] = new Switchery(document.querySelector('#isMember'), {color: "#1AB394"}) : ""
    if (data.isMember == 1) {
        setSwitchery(editsw["isMember"], true);
    } else {
        setSwitchery(editsw["isMember"], false);
    }
    editsw["isJifen"] == undefined ? editsw["isJifen"] = new Switchery(document.querySelector('#isJifen'), {color: "#1AB394"}) : ""
    if (data.isJifen == 1) {
        setSwitchery(editsw["isJifen"], true);
    } else {
        setSwitchery(editsw["isJifen"], false);
    }
    editsw["isCoupon"] == undefined ? editsw["isCoupon"] = new Switchery(document.querySelector('#isCoupon'), {color: "#1AB394"}) : ""
    if (data.isCoupon == 1) {
        setSwitchery(editsw["isCoupon"], true);
    } else {
        setSwitchery(editsw["isCoupon"], false);
    }
    editsw["isRecommended"] == undefined ? editsw["isRecommended"] = new Switchery(document.querySelector('#isRecommended'), {color: "#1AB394"}) : ""
    if (data.isRecommended == 1) {
        setSwitchery(editsw["isRecommended"], true);
    } else {
        setSwitchery(editsw["isRecommended"], false);
    }
    modal.find('#maxUseJifen').val(data.maxUseJifen)
    modal.find('#hasSku').val(data.hasSku)
    $('#snpackinglist2').code(data.packinglist);
    $('#packinglist2').val(data.packinglist);
    $('#snafterservice2').code(data.afterservice);
    $('#afterservice2').val(data.afterservice);
    $('#snintroduction2').code(data.introduction);
    $('#introduction2').val(data.introduction);
    modal.find('#gtype').find("option[value='" + data['gtype'] + "']").attr("selected", true);
    modal.find('#modifier').val(data.modifier)

})

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

$(function () {

    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })
    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/goodssku/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 50,//单页记录数
        pageList: [50, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '商品分类',
                field: 'cid'
            },
            {
                title: '商品卖点',
                field: 'characteristic'
            },
            {
                title: '物流模板编号',
                field: 'logisticsId'
            },
            {
                title: '最低价',
                field: 'minPrice'
            },
            {
                title: '商品原价',
                field: 'price'
            },
            {
                title: '实际售价',
                field: 'saleprice'
            },
            {
                title: '商品名',
                field: 'name'
            },
            {
                title: '收藏数',
                field: 'numberFav'
            },
            {
                title: '好评数',
                field: 'numberGrade'
            },
            {
                title: '订单数',
                field: 'numberOrders'
            },
            {
                title: '销量数',
                field: 'numberSale'
            },
            {
                title: '排序',
                field: 'paixu'
            },
            {
                title: '起售时间',
                field: 'dateStart'
            },
            {
                title: '停售时间',
                field: 'dateEnd'
            },
            {
                title: '规格',
                field: 'propertyIds'
            },
            {
                title: '推荐指数',
                field: 'recommend'
            },
            {
                title: '启用状态',
                field: 'state',
                formatter: "stateFormatter"
            },
            {
                title: '总库存数',
                field: 'stores'
            },
            {
                title: '商品视频',
                field: 'videoId'
            },
            {
                title: '商品主图',
                field: 'pic',
                formatter: "imgFormatter"
            },
            {
                title: '可扣除优惠券',
                field: 'maxUseCoupon'
            },
            {
                title: '分享奖励类型',
                field: 'shareBonusType',
                formatter: "shareBonusTypeFormatter"
            },
            {
                title: '奖励额',
                field: 'shareMount'
            },
            {
                title: '商品二维码',
                field: 'barcode'
            },
            {
                title: '商品重量：KG',
                field: 'weight'
            },
            {
                title: '浏览量',
                field: 'views'
            },
            {
                title: '营销活动',
                field: 'eventId'
            },
            {
                title: '是否支持会员卡交易',
                field: 'isMember',
                formatter: "sfFormatter"
            },
            {
                title: '是否支持积分抵扣交易',
                field: 'isJifen',
                formatter: "sfFormatter"
            },
            {
                title: '是否支持优惠券交易',
                field: 'isCoupon',
                formatter: "sfFormatter"
            },
            {
                title: '是否热推',
                field: 'isRecommended',
                formatter: "sfFormatter"
            },
            {
                title: '可扣除积分',
                field: 'maxUseJifen'
            },
            {
                title: '是否含有sku产品',
                field: 'hasSku'
            },
            {
                title: '产品类型',
                field: 'gtype',
                formatter: "gtypeFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 170,
                formatter: actionFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    })

    //请求服务数据时所传参数
    function queryParams(params) {
        console.log(params)
        return params;
    }

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });

    $('#info').val($('#sninfo').code())
    if ($("#hidpic").attr("required") == "required"
        && $("#hidpic").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }
    $('#packinglist').val($('#snpackinglist').code())
    $('#afterservice').val($('#snafterservice').code())
    $('#introduction').val($('#snintroduction').code())
    return true;
}

function checkModify() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });

    $('#info2').val($('#sninfo2').code())
    if ($("#hidpic2").attr("required") == "required"
        && $("#hidpic2").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }
    $('#packinglist2').val($('#snpackinglist2').code())
    $('#afterservice2').val($('#snafterservice2').code())
    $('#introduction2').val($('#snintroduction2').code())
    return true;
}